<?php

namespace App\Models\OpenShop\Common;

use App\Models\BaseModel;
use App\Models\Shop\ShopModel;
use App\Models\Traits\KfSoftDeletes;
use App\Service\OpenShop\Feishu\PermissionService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class OpenShopOrderManagerModel extends BaseModel
{
    use HasFactory, KfSoftDeletes;

    const MANAGER_TYPE_1 = 1;
    const MANAGER_TYPE_2 = 2;
    const MANAGER_TYPE_3 = 3;
    const MANAGER_TYPE_4 = 4;
    const MANAGER_TYPE_5 = 5;


    const TYPE_MAP = [
        self::MANAGER_TYPE_1 => "招商顾问",
        self::MANAGER_TYPE_2 => "开发顾问",
        self::MANAGER_TYPE_3 => "设计顾问",
        self::MANAGER_TYPE_4 => "筹备顾问",
        self::MANAGER_TYPE_5 => "督导",//营运顾问(督导)
    ];

    //修改顾问权限的映射
    const ORDER_CHANGE_MANAGER_MAPPING = [
        self::MANAGER_TYPE_1 => PermissionService::ORDER_CHANGE_MANAGER_1,
        self::MANAGER_TYPE_2 => PermissionService::ORDER_CHANGE_MANAGER_2,
        self::MANAGER_TYPE_3 => PermissionService::ORDER_CHANGE_MANAGER_3,
        self::MANAGER_TYPE_4 => PermissionService::ORDER_CHANGE_MANAGER_4,
        self::MANAGER_TYPE_5 => PermissionService::ORDER_CHANGE_MANAGER_5,
    ];

    const NORMAL  = 0;
    const DELETED = 1;

    const ORDER_STATUS_NORMAL  = 1;
    const ORDER_STATUS_INVALID = 0;

    const ORDER_STATUS_MAP = [
        self::ORDER_STATUS_NORMAL  => "正常",
        self::ORDER_STATUS_INVALID => "作废"
    ];

    protected $table    = "open_shop_order_manager";
    protected $fillable = [
        'mainProcessId',
        'type',
        'managerUid',
        'managerName',
        'description',
        'orderStatus',
        'isDeleted',
        'shopId',
    ];


    /**
     * @param int $type
     * @param int $mainProcessId
     * @param int $managerId
     * @param string $managerName
     * @param int $orderStatus
     * @param int $shopId
     * @return bool
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function generateManagerOrUpdate(
        int $type,
        int $mainProcessId,
        int $managerId,
        string $managerName,
        int $orderStatus = self::ORDER_STATUS_NORMAL,
        int $shopId = 0
    ): bool {
        $rmsUser = getRmsUserInfoByAuth();

        self::query()
            ->where("mainProcessId", $mainProcessId)
            ->where("type", $type)
            ->update([
                "isDeleted"    => self::DELETED,
                "updatedAt"    => time(),
                "updatedByUid" => $rmsUser ? $rmsUser->id : 0
            ]);

        return self::query()->insert([
            "mainProcessId" => $mainProcessId,
            "type"          => $type,
            "managerUid"    => $managerId,
            "managerName"   => $managerName,
            "description"   => self::TYPE_MAP[$type],
            "orderStatus"   => $orderStatus,
            "createdAt"     => time(),
            "updatedAt"     => time(),
            "createdByUid"  => $rmsUser ? $rmsUser->id : 0,
            'shopId'        => $shopId,
        ]);
    }

    /**
     * @param int $mainProcessId
     * @return int
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function invalidOrderManager(int $mainProcessId): int
    {
        $rmsUser = getRmsUserInfoByAuth();
        return self::query()
                   ->where("mainProcessId", $mainProcessId)
                   ->where("isDeleted", self::NORMAL)
                   ->update([
                       "orderStatus"  => self::ORDER_STATUS_INVALID,
                       "updatedAt"    => time(),
                       "updatedByUid" => $rmsUser ? $rmsUser->id : 0
                   ]);
    }

    public static function getManagerUid(int $mainProcessId, int $type): int
    {
        return (int)self::query()->where('mainProcessId', $mainProcessId)->where('type', $type)->value('managerUid');
    }

    /**
     * 通过督导查询关联门店
     * @param array $userIds
     * @param Builder|null $childMainProcessIds
     * @return array
     */
    public static function getShopIdByUid(array $userIds, Builder $childMainProcessIds = null): array
    {
        $shopRelData = [];
        OpenShopOrderManagerModel::query()
            ->when($childMainProcessIds, function ($query) use ($childMainProcessIds) {
                $query->whereRaw('mainProcessId in (' . BaseModel::toSqlWithParam($childMainProcessIds) . ')');
            })
            ->whereIn('managerUid', $userIds)
            ->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_5)// 督导
            ->where('orderStatus', OpenShopOrderManagerModel::ORDER_STATUS_NORMAL)// 正常
            ->select(['managerUid', 'shopId'])
//            ->groupBy('shopId')
            ->get()
            ->map(
                function ($item) use (&$shopRelData) {
                    $shopId = $item->shopId ?? 0;
                    if ($shopId) {
                        $shopRelData[$item->managerUid][] = $shopId;
                    }
                }
            );
        return $shopRelData;
    }

    public function shopRel(): HasOne
    {
        return $this->hasOne(ShopModel::class, 'id', 'shopId');
    }

    /**
     * 查询当前督导关联的门店
     * @param array $shopIds
     * @param array $userIds
     * @return array
     */
    public static function getNotRelShopIdByUid(array $shopIds, array $userIds): array
    {
        $shopData = [];
        OpenShopOrderManagerModel::query()
            ->with(['shopRel'])
            ->whereIn('shopId', $shopIds)
            ->where('managerUid', '>', 0)
            ->whereNotIn('managerUid', $userIds)
            ->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_5)// 督导
            ->where('orderStatus', OpenShopOrderManagerModel::ORDER_STATUS_NORMAL)// 正常
            ->groupBy('shopId')
            ->get()
            ->map(
                function ($item) use (&$shopData) {
                    $shopData[] = [
                        'shopId'      => $item->shopRel->id ?? 0,
                        'shopName'    => $item->shopRel->name ?? '',
                        'shopCode'    => $item->shopRel->shopCode ?? '',
                        'managerUid'  => $item->managerUid ?? 0,
                        'managerName' => $item->managerName ?? '',
                    ];
                }
            );
        return $shopData;
    }
}
